﻿using PKTools.Database;
using PKTools.Scheduler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Scheduler
{
    class Config : TaskExecutorConfig
    {
        public override Sql SqlCreate(bool openTransaction = false, string connection = null)
        {
            return new MsSql(openTransaction, connection);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var
                schedule = new Schedule
                {
                    Type = Schedule._Type.Interval,
                    Interval = new TimeSpan(0, 0, 1, 0)
                };
            var
                jobSchedule = new JobSchedule()
                {
                    Schedule = schedule
                };

            using (var sql = new MsSql(true))
            {
                sql.Insert(jobSchedule);

                var
                    job = sql.LoadByPK<Job>(1);

                job.LEET = DateTime.UtcNow.AddMonths(-1);
                job.JobScheduleID = jobSchedule.ID;
                job.LastJobHistoryID = null;

                sql.Update(job);

                sql.DeleteAll<JobTask>();
                sql.DeleteAll<JobStepHistory>();
                sql.DeleteAll<JobHistory>();

                if (job.Schedule(DateTime.UtcNow))
                {
                    job.GetFirstStep().CreateTask();
                }

                sql.Commit();
            }

            var
                executor = new TaskExecutor(new TaskDispatcher(), new Config());

            executor.Start();

            Console.Write("press enter to stop ...");
            Console.ReadLine();

            executor.Stop();
        }
    }
}
